import EnemyProps from "../EnemyProps";
import RoadPointScript from './RoadPointScript'
import EnemySpawner from "./EnemySpawner";
import Bullet from "./Bullet";
import Tools from "../Tools";
import StageScene from "./StageScene";
var Vector3 = Laya.Vector3
export default class Enemy extends Laya.Script3D {
  private enemy: Laya.Sprite3D
  private currIndex: number
  private pointArr = RoadPointScript.pointArr
  private prop: EnemyProps
  private blood: number
  private type: number
  private static effectArr: Array<Laya.Sprite3D>
  private props: Array<EnemyProps> = [
    {
      blood: 150,
      speed: .015,
      deadPath: 'res/atlas/Models/Conventional/Enemy0Dead.lh'
    }, {
      blood: 250,
      speed: .020,
      deadPath: 'res/atlas/Models/Conventional/Enemy1Dead.lh'
    }, {
      blood: 350,
      speed: .025,
      deadPath: 'res/atlas/Models/Conventional/Enemy2Dead.lh'
    }, {
      blood: 450,
      speed: .030,
      deadPath: 'res/atlas/Models/Conventional/Enemy3Dead.lh'
    },
  ]
  onEnable() {
    this.enemy = this.owner as Laya.Sprite3D
    this.currIndex = 0
    this.type = parseInt(this.enemy.name)
    this.prop = this.props[this.type]
    this.blood = this.prop.blood
    Enemy.effectArr = new Array(4)
  }

  onUpdate() {
    // 敌人移动
    this.move()
  }

  private move() {
    var direct = new Vector3()
    Vector3.subtract(this.pointArr[this.currIndex], this.enemy.transform.position, direct)
    Vector3.normalize(direct, direct)
    Vector3.scale(direct, this.prop.speed * Laya.timer.delta, direct)
    this.enemy.transform.translate(direct)

    if (Vector3.distance(this.enemy.transform.position, this.pointArr[this.currIndex]) < 0.3) {
      if (this.currIndex < this.pointArr.length - 1) this.currIndex++
      // 到达终点
      else {
        this.enemy.destroy()
        EnemySpawner.instance.judgeWaveDown()
        // 游戏失败
      }
    }
  }

  onCollisionEnter(collision) {
    if(!collision.other.owner) return
    // console.log('被攻击')
    let bullet = collision.other.owner.getComponent(Bullet) as Bullet
    if(!bullet) bullet = collision.other.owner.parent.getComponent(Bullet) as Bullet
    // 扣血
    this.blood -= bullet.props[bullet.type].power
    bullet.destroyeBullet()
    // 设置死亡效果
    if (this.blood <= 0) this.setEffect()
  }             

  private setEffect() {
    let effect = Enemy.effectArr[this.type]
    if (!effect) Enemy.effectArr[this.type] = Laya.loader.getRes('res/atlas/Models/Conventional/Enemy' + this.type + 'Dead.lh')
    effect = Enemy.effectArr[this.type]
    let ef = Laya.Sprite3D.instantiate(effect, StageScene.instance.stageScene, false, this.enemy.transform.position)
    Tools.destroy(this.enemy)
    StageScene.instance.setCoin(-(this.type + 1) * 50)
    EnemySpawner.instance.judgeWaveDown()
    Tools.destroy(ef, 300)
  }
}